package com.bxw.forum.service.impl;

import com.bxw.forum.common.AppResult;
import com.bxw.forum.common.ResultCode;
import com.bxw.forum.dao.ArticleReplyMapper;
import com.bxw.forum.exception.ApplicationException;
import com.bxw.forum.model.ArticleReply;
import com.bxw.forum.service.IArticleReplyService;
import com.bxw.forum.service.IArticleService;
import com.bxw.forum.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;


@Slf4j
@Service
public class ArticleReplyServiceImpl implements IArticleReplyService {

    @Resource
    private ArticleReplyMapper articleReplyMapper;

    @Resource
    private IArticleService articleService;

    /**
     * 新增回复
     * @param articleReply 回复对象
     */
    @Override
    public void create(ArticleReply articleReply) {
        //校验必传数据
        if(articleReply == null
                || articleReply.getArticleId() == null
                || articleReply.getPostUserId() == null
                || StringUtils.isEmpty(articleReply.getContent())) {

            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());

            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_PARAMS_VALIDATE));
        }


        //将默认值赋值
        articleReply.setReplyId(null);
        articleReply.setReplyUserId(null);
        articleReply.setLikeCount(null);
        articleReply.setState((byte)0);
        articleReply.setDeleteState((byte)0);
        Date date = new Date();
        articleReply.setCreateTime(date);
        articleReply.setUpdateTime(date);
        //调用DAO插入数据
        int row = articleReplyMapper.insertSelective(articleReply);
        //校验是否插入成功
        if(row != 1) {
            log.warn(ResultCode.ERROR_SERVICES.toString());

            throw new ApplicationException(AppResult.fail(ResultCode.ERROR_SERVICES));
        }
        //调用DAO将帖子回复数量加一
        articleService.addOneReplyCountById(articleReply.getArticleId());

        log.info("回复成功, article id = " + articleReply.getArticleId() + ", user id = " +
                articleReply.getPostUserId());
    }

    /**
     * 根据帖子ID查询该帖子下的所有回复
     * @param articleId 帖子ID
     * @return
     */
    @Override
    public List<ArticleReply> selectByArticleId(Long articleId) {

        if(articleId == null || articleId <= 0) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());

            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        List<ArticleReply> articleReplies = articleReplyMapper.selectByArticleId(articleId);

        return articleReplies;
    }
}
